package preparedStatement;

import java.sql.*;

public class MysqlTest {

    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/";
    private static final String DATABASE_NAME = "test";
    private static final String DATABASE_USERNAME = "root";
    private static final String DATABASE_PASSWORD = "root";

    public static void main(String[] args) {
        try {

            //1.注册数据库驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //Class.forName("com.mysql.jdbc.Driver");
            System.out.println("注册驱动成功!");
        } catch (Exception e1) {
            System.out.println("注册驱动失败!");
            e1.printStackTrace();
            return;
        }

        String url = DATABASE_URL + DATABASE_NAME;
        Connection conn = null;
        try {

            //2.创建并获取数据库连接
            conn = DriverManager.getConnection(url, DATABASE_USERNAME, DATABASE_PASSWORD);

            //3.设置preparedStatement对象
            PreparedStatement stmt = conn.prepareStatement("select id,username from user order by id desc limit ?,?");
            System.out.println("创建PreparedStatement成功！");

            //4.为preparedStatement绑定参数
            stmt.setInt(1, 0);
            stmt.setInt(2, 3);

            //4.通过preparedStatement执行SQL语句并获取结果
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                //5.对结果集进行解析处理
                System.out.println(rs.getInt(1) + "," + rs.getString(2));
            }

            //6.释放资源。顺序：ResultSet→preparedStatement→Connection
            rs.close();
            stmt.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != conn) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}